/**
 * 
 */
package any.restlet;

import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.restlet.Context;
import org.restlet.Directory;
import org.restlet.data.Form;
import org.restlet.data.LocalReference;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO: doc me
 * 
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 60 $
 * @version
 */
public class GWTDirectory extends Directory {
	private static final Logger	LOG	= LoggerFactory
	                                        .getLogger(GWTDirectory.class);

	public GWTDirectory(final Context context,
	        final Reference rootLocalReference) {
		super(context, rootLocalReference);
	}

	public GWTDirectory(final Context context, final String rootUri) {
		super(context, rootUri);
	}

	@Override
	public void handle(final Request request, final Response response) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("To handle {}", request.getResourceRef());
		}
		super.handle(request, response);
		final String uri = request.getResourceRef().toString();

		if (-1 != uri.indexOf(".nocache.")) {
			Form form = (Form) response.getAttributes().get(
			        "org.restlet.http.headers");
			if (form == null) {
				form = new Form();
				response.getAttributes().put("org.restlet.http.headers", form);
			}
			response.getEntity().setExpirationDate(new Date());
			form.set("Pragma", "no-cache", true);
		} else {
			final Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.YEAR, 1);
			response.getEntity().setExpirationDate(calendar.getTime());
			final LocalReference localReference = new LocalReference(response
			        .getEntity().getIdentifier());
			final ClassLoader loader = Thread.currentThread()
			        .getContextClassLoader();
			String path = localReference.getPath();

			// Prepare a classloader URI, removing the leading slash
			if (path != null && path.startsWith("/")) {
				path = path.substring(1);
			}
			// As the path may be percent-encoded, it has to be percent-decoded.
			final URL url = loader.getResource(Reference.decode(path));
			try {
				final Date date = new Date(url.openConnection()
				        .getLastModified());
				response.getEntity().setModificationDate(date);
				response.getEntity().setTag(
				        new Tag(DigestUtils.md5Hex(date.toString()), true));
			} catch (final IOException e) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Unable to open connection", e);
				}
			}
		}
	}
}
